/*
 * 路由模块
 * */
let express=require('express')
let router=express.Router()
let fs=require('fs')

let student=require('./students')

router.get('/',function (req,res) {
     student.find(function (err,students) {
        if(err){
            return res.status(500).send('Serve Error')
        }
        res.render('index.html',{
            students:students
        })
    })
    })
router.get('/students',function (req,res) {
   student.find(function (err,students) {
        if(err){
            return res.status(500).send('Serve Error')
        }
         res.render('index.html',{
            students:students
        })
    })

})

router.get('/students/new',function (req,res) {
       res.render('new.html')
})

router.post('/students/new',function (req,res) {
    //获取表单数据----req.body
      student.save(req.body,function (err) {
           if(err){
               return res.status(500).send('Serve Error')
           }
           res.redirect('/')
      })

})

router.get('/students/edit',function (req,res) {
 student.findById(parseInt(req.query.id),function (err,student) {
       if(err){
           return res.status(500).send('Serve Error')
       }
       res.render('edit.html',{
           student:student
       })

 })

})

router.post('/students/edit',function (req,res) {
    student.undataById(req.body,function (err) {
        if(err){
            return res.status(500).send('Serve Error')
        }
        res.redirect('/students')
    })
})

router.get('/students/delete',function (req,res) {
   student.deleteById(req.query.id,function (err) {
       if(err){
           return res.status(500).send('Serve Error')
       }
       res.redirect('/students')
   })


})


module.exports=router

